import { Injectable } from '@nestjs/common';
import { CreateNoticeDto } from './dto/create-notice.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { resultUtil } from 'src/utils/result';
import * as dayjs from 'dayjs';


@Injectable()
export class NoticeService {
  constructor(private readonly prismaService: PrismaService){}
  /**
   * 新增公告
  */
  async create(createNoticeDto: CreateNoticeDto) {
    await this.prismaService.notice.create({
      data: {
        ...createNoticeDto
      }
    })
    return resultUtil('', '000000')
  }
  /**
   *获取公告列表
  */
  async query(queryInfo) {
    const { content, currentPage, pageSize, publish } = queryInfo;
    const skip = (currentPage - 1) * pageSize;
    const where = {} as any;
    if (content) {
      where.content = { contains: content };
    }
    // 在门户的时候只查询发布的公告
    if (+publish) {
      where.publish = true
    }
    const [records, total] = await Promise.all([
      this.prismaService.notice.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          id: 'desc',
        },
      }),
      this.prismaService.notice.count({ where }),
    ]);
    return resultUtil('', '000000', {
      records: records?.map((item: any) => {
        let result = {
          ...item,
          createdAt: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
        }
        return result
      }),
      total: total,
    });
  }
    /**
 * 删除公告
 */
  async delete(id: number) {
    await this.prismaService.notice.delete({
      where: { id: +id },
    });
    return resultUtil('', '000000');
  }
  /**
   * 发布公告
  */
  async publish(info) {
    await this.prismaService.notice.update({
      where: { id: +info.id },
      data: {
        publish: info.publish
      },
    });
    return resultUtil('', '000000');
  }
  /**
   * 更新公告
  */
  async update(info) {
    await this.prismaService.notice.update({
      where: { id: +info.id },
      data: {
        content: info.content
      }
    })
    return resultUtil('', '000000')
  }
}
